package swa.telco.impl;


import java.net.URI;

import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;

import swa2012.telco.broker.Broker;
import swa2012.telco.broker.BrokerCallback;
import swa2012.telco.broker.beans.BrokerRegistrationStatus;
import swa2012.telco.broker.beans.Provider;

public class SWAProvider {
	private static final String providerID = "group01";
	private static final String brokerURI = "https://swa.univie.ac.at/TelcoBroker/BrokerService";
	
	private Broker broker;
	private BrokerCallback brokerCb;
	private ImplClientProvider clientProvider;
	private Provider provider;
	private OnlineClients onlineClients = new OnlineClients();
	private MessageContainer messageContainer = new MessageContainer();
	
	private StringBuffer logString;
	
	public SWAProvider(StringBuffer logString) {
		clientProvider = new ImplClientProvider(this, onlineClients, messageContainer);
		brokerCb = new ImplBrokerCallback(messageContainer, onlineClients);
		
		JaxWsProxyFactoryBean jwsfactoryb = new JaxWsProxyFactoryBean();
		jwsfactoryb.setServiceClass(Broker.class);
		jwsfactoryb.setAddress(brokerURI);
		
		broker = (Broker)jwsfactoryb.create();
		
		this.logString = logString;
		
		logString.append("ClientProvider : " + clientProvider + "\n");
		logString.append("BrokerCallback : " + brokerCb + "\n");
	}
	
	public Provider getBeanOfProvider(){
		return provider;
	}
	
	public Broker getBroker(){
		return broker;
	}
	
	public void startCallBack(URI uriEndpoint){
		//TODO check Availability of Service //
		provider = new Provider(providerID, uriEndpoint);
		BrokerRegistrationStatus stat = broker.registerProvider(provider);
		logString.append("Provider Registration Status : " + stat  + "\n");
	}
	
	public void stop(){
		BrokerRegistrationStatus stat = broker.deregisterProvider(provider);
		
		logString.append("Provider Registration Status (deregistration) : " + stat + "\n");
	}

	public BrokerCallback getBrokerCb(){
		return brokerCb;
	}
	
	public ImplClientProvider getClientProvider(){
		return clientProvider;
	}
}
